package com.serve.oa.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.serve.oa.entity.SysMenu;
import com.serve.oa.entity.SysUser;
import com.serve.oa.mapper.SysRoleMapper;
import com.serve.oa.mapper.SysUserMapper;
import com.serve.oa.service.SysMenuService;
import com.serve.oa.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Synchronized;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author __tyw
 * @since 2022-10-18
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService, InitializingBean {


    @Autowired
    RabbitTemplate rabbitTemplate;



    @Autowired
    SysUserMapper userMapper;

    @Autowired
    SysRoleMapper sysRoleMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    SysUserService sysUserService;

    @Autowired
    SysMenuService sysMenuService;


    @Override
    public HashSet<String> getPerm(String userName){



        if(redisTemplate.hasKey("perm:"+userName)){
            String sax = (String) redisTemplate.opsForValue().get("perm:"+userName);
            String[] data = StringUtils.tokenizeToStringArray(sax, ",");
            HashSet<String> arr  = new HashSet<>();
            for(String str :data) {
                arr.add(str);
            }
            return arr;
        }else {

            SysUser user =  sysUserService.getOne(new QueryWrapper<SysUser>().eq("username",userName));
            List<SysMenu>  list = userName.equals("admin") ? sysMenuService.list()  :  userMapper.listGetMenuByUserId(user.getId());
            HashSet<String> arr  = new HashSet<>();
            String p = "";
            //System.out.println(list.toString());
            for(SysMenu item:list){
                arr.add(item.getPerms());
                p = p.concat("," + item.getPerms());
            }
            p = p.substring(1);
            redisTemplate.opsForValue().set("perm:"+userName,p,60*60, TimeUnit.SECONDS);

            return arr;
        }

    }



    @Override
    @DS("db2")
    public List<Map> listAll() {
        return userMapper.listAll();
    }

    @Override
    public List<SysUser> chaList() {
        return userMapper.chaList();
    }




    @Override
    @Cacheable(value = {"time"}, key = "'shijian'")
    public String getTime(String id) {
        return LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME);
    }



    @Override

    public Map myMenu(Long id) {

        List<SysMenu>  list = userMapper.listGetMenuByUserId(id);



        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
// 自定义属性名 都要默认值的
        treeNodeConfig.setNameKey("name");
        treeNodeConfig.setIdKey("id");
        treeNodeConfig.setParentIdKey("parentId");
        treeNodeConfig.setChildrenKey("children");

        treeNodeConfig.setDeep(3);


//转换器


        List<Tree<String>> treeNodes = TreeUtil.build(list, "0",treeNodeConfig,(treeNode, tree)->{
            tree.setId(treeNode.getId().toString());
            tree.setParentId(treeNode.getParentId().toString());
            tree.setName(treeNode.getName());

            tree.putExtra("path", treeNode.getPath());
            tree.putExtra("perms", treeNode.getPerms());
            tree.putExtra("component", treeNode.getComponent());


        });

        ArrayList<String> alist  =  new ArrayList();
        list.forEach(i->{
            alist.add(i.getPerms());
        });

        Map map = new HashMap();
        map.put("menu",treeNodes);
        map.put("perm",alist);


        return map;


    }





    @Override
    @Transactional
    public void dx(String s) throws InterruptedException {
       // userMapper.jiansql();
        userMapper.addOrder(s);


        TimeUnit.SECONDS.sleep(1);
        System.out.println("发送了短信---"+s);

    }

    @Override
    @Transactional
    public void emalis(String s) throws InterruptedException {


      //  userMapper.jiansql();
        userMapper.addOrder(s);

        TimeUnit.SECONDS.sleep(3);

        System.out.println("发送了emails---"+s);

    }

    @Override
    public List<Map> dsd(){
      return userMapper.dsd();
    }
    @Override
    public void sendMsg(String msg){

        redisTemplate.opsForValue().decrement("kc001");
        rabbitTemplate.convertAndSend("reg007",msg);
    }


    @Override
    public void startSeckillInit() {

        List<Map> dsd = sysUserService.dsd();
        Integer SAD = (Integer) dsd.get(0).get("stock");
        redisTemplate.opsForValue().set("kc001",SAD);

    }


    @Override
    @Synchronized
    public boolean qd() {
        Map m = userMapper.cx();

        m.put("cout", (int)m.get("cout") - 1);
        System.out.println(m);

        int a = userMapper.qd(m);
        System.out.println(a);

        return true;


    }


    //页面初始化缓存
    @Override
    public void afterPropertiesSet() throws Exception {
        this.startSeckillInit();
    }
}
